package cn.wolfcode.wms.service.impl;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.mapper.EmployeeMapper;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.query.PageResult;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IEmployeeService;
import cn.wolfcode.wms.util.LogicRuntimeException;
import cn.wolfcode.wms.util.MD5;
import cn.wolfcode.wms.util.UserContext;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

	@Autowired
	private EmployeeMapper mapper;
	@Autowired
	private PermissionMapper permissionMapper;

	@Override
	public void save(Employee employee, Long[] ids) {
		//加密
		String password = MD5.encode(employee.getPassword());
		employee.setPassword(password);
		mapper.save(employee);
		if (ids != null) {
			for (Long id : ids) {
				mapper.saveRoleAndEmployeeRelation(employee.getId(), id);
			}
		}
	}

	@Override
	public void delete(Long id) {
		// 删除关系
		mapper.deleteRoleAndEmployeeRelation(id);
		mapper.delete(id);
	}

	@Override
	public void update(Employee employee, Long[] ids) {
		mapper.update(employee);
		mapper.deleteRoleAndEmployeeRelation(employee.getId());
		if (ids != null) {
			for (Long id : ids) {
				mapper.saveRoleAndEmployeeRelation(employee.getId(), id);
			}
		}
	}

	@Override
	public Employee get(Long id) {
		return mapper.get(id);
	}

	@Override
	public List<Employee> list() {
		return mapper.list();
	}

	@Override
	public PageResult query(QueryObject qo) {
		int totalCount = mapper.queryForCount(qo);
		if (totalCount == 0) {
			return new PageResult(qo.getPageSize());
		}
		List<Employee> listData = mapper.queryForList(qo);
		return new PageResult(qo.getCurrentPage(), qo.getPageSize(), listData, totalCount);
	}

	@Override
	public void selectByUsernameAndPassword(String username, String password) {
		//调用mapper中的方法根据用户名和密码查询是否有该用户
		
		Employee currentUser = mapper.selectByUsernameAndPassword(username, MD5.encode(password));
		
		if (currentUser == null) {
			throw new LogicRuntimeException("账号或密码错误,请重新登录");
		}
		// 将用户信息添加到Session作用域中
		// 如何获取到Session对象
		UserContext.setUser(currentUser);
		// 将用户拥有的所有的权限的表达式添加到session中
		// 根据当前用户的id去数据库中查询出对应的权限表达式
		Set<String> expressions = permissionMapper.selectAllExpressionsByEmpId(currentUser.getId());
		UserContext.setExpressions(expressions);
	}
}
